<template>
	<view class="login-container">
		<!-- 提示登录的图标 -->
		<uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
		<!-- 登录按钮 -->
		<button type="primary" class="btn-login" @click="getUserProfile">一键登录</button>
		<!-- 登录提示 -->
		<view class="tips-text">
			登录后尽享更多权益
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {
				query: {}
			};
		},
		computed: {
			...mapState('m_user', ['redirectInfo'])
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
			getUserProfile() {
				uni.getUserProfile({
					desc: '用于完善用户资料',
					success: (res) => {
						this.updateUserInfo(res.userInfo)
						// 获取登录成功后的token值
						this.getToken(res)

					},
					fail: () => {
						uni.$showMsg('获取用户信息失败')
					}
				})
			},

			// 调用登录接口获取code凭证,去换取token
			async getToken(info) {
				let query = {}
				const [err, res] = await uni.login();
				query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawDate: info.rawData,
					signature: info.signature
				}

				// 换取token
				// const {
				// 	data: loginResult
				// } = await uni.$http.post('/users/wxlogin', query)
				// console.log(loginResult);
				// if (loginResult.meta.status !== 200) return uni.$showMsg('获取不到token登录失败')
				// uni.$showMsg('登录成功！')
				// 更新vuex的token
				this.updateToken('dav')

				// 判断是否需要重定向,即判断vuex中的redirectInfo是否为null
				// 如果不为null,则登录成功后重新导航到对应界面
				this.navigateRedirect()

			},
			navigateRedirect() {
				if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
					uni.switchTab({
						url: this.redirectInfo.from,
						complete: () => {
							this.updateRedirectInfo(null)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.login-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 750rpx;
		background-color: #ececec;
		position: relative;
		overflow: hidden;

		&::after {
			content: '';
			display: block;
			position: absolute;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 40px;
			background-color: #fff;
			border-radius: 100%;
			transform: translateY(50%);
		}

		.btn-login {
			width: 90%;
			border-radius: 100px;
			margin: 15px 0;
			background-color: #c00000;
		}

		.tips-text {
			font-size: 12px;
			color: gray;
		}
	}
</style>
